//
//  AddressBookViewController.m
//  MooreDoll
//
//  Created by 郭景豪 on 2014/12/1.
//  Copyright (c) 2014年 Tank. All rights reserved.
//

#import "AddressBookViewController.h"
#import "AddressCell.h"
#import "WinkAlertView.h"
#import "UIImageView+AFNetworking.h"
#import "TelephonyInfo.h"
#import "UIImageView+AFNetworking.h"
#import "SelectFiedViewController.h"
@interface AddressBookViewController ()<FiendFriendDelegate,UIAlertViewDelegate>

@end

@implementation AddressBookViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //拿取聯絡人
    [GetAddressBook sharedInstance].delegate = self;
    [[GetAddressBook sharedInstance]addressBookGetAuthorizationStatus];

}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"selectCellSet"]) {
        if ([self.selectCellSet count]==0) {
            [self.BT_JoinFriend setEnabled:NO];
        }else
        {
            [self.BT_JoinFriend setEnabled:YES];
        }
    }
}

- (void)dealloc
{
    
    [self removeObserver:self forKeyPath:@"selectCellSet"];
}

-(void)viewDidAppear:(BOOL)animated
{
    

}
#pragma mark 確認取得聯絡人狀態
-(void)isAddressBookGetAuthorizationStatus
{
    //檢查聯絡人取得的數量
    if ([GetAddressBook sharedInstance].MA_UserAddressBook.count > 0) {
        
        NSMutableArray *addressBookArray = [GetAddressBook sharedInstance].MA_UserAddressBook;
        
        if ([UIAlertController class])
        {
            // use UIAlertController
            self.alertController= [UIAlertController
                                   alertControllerWithTitle:@"搜尋中"
                                   message:@"請等待..."
                                   preferredStyle:UIAlertControllerStyleAlert];
            
            [self presentViewController:self.alertController animated:YES completion:^{
                
                [FiendFriend sharedInstance].delegate = self;
                
                //取的有在使用的聯絡人 jid
                [[FiendFriend sharedInstance]searchFreindForServer:addressBookArray];
            }];
        }
        else
        {
            // use UIAlertView
            self.AV_Loaging = [[UIAlertView alloc]initWithTitle:@"搜尋中" message:@"請等待..." delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
            [self.AV_Loaging show];
            
            [FiendFriend sharedInstance].delegate = self;
            
            //取的有在使用的聯絡人 jid
            [[FiendFriend sharedInstance]searchFreindForServer:addressBookArray];
        }
        
        
        
        
    }else
    {
        [WinkAlertView _showAlertViewHaveDelegateWithTitle:@"注意" content:@"無聯絡人" cancelButtonTitle:@"OK" showTime:3.0f delegate:self];
    }
    
    self.selectCellSet = [[NSMutableSet alloc]initWithCapacity:0];
    
    [self addObserver:self forKeyPath:@"selectCellSet" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
}


-(void)getVcardResult:(id)responseObject
{
    if ([responseObject count]>0) {
        
        self.friendRosterVcard = responseObject;
        [self.addressBookTableView reloadData];
        
        if ([UIAlertController class])
        {
            
            [self.alertController dismissViewControllerAnimated:YES completion:nil];
            
        }else
        {
            [self.AV_Loaging dismissWithClickedButtonIndex:0 animated:YES];
            
        }
    }else
    {
        if ([UIAlertController class])
        {
            
            [self.alertController dismissViewControllerAnimated:YES completion:nil];
            
        }else
        {
            [self.AV_Loaging dismissWithClickedButtonIndex:0 animated:YES];
            
        }
//        [WinkAlertView _showAlertViewHaveDelegateWithTitle:@"注意" content:@"無朋友使用MD" cancelButtonTitle:@"OK" showTime:3.0f delegate:self];

    }
}
-(void)errorNotFindFriend
{
    if ([UIAlertController class])
    {
        
        [self.alertController dismissViewControllerAnimated:YES completion:nil];
        
    }else
    {
        [self.AV_Loaging dismissWithClickedButtonIndex:0 animated:YES];

    }
//    [WinkAlertView _showAlertViewHaveDelegateWithTitle:@"注意" content:@"無朋友使用MD" cancelButtonTitle:@"OK" showTime:3.0f delegate:self];
    //判斷 如果成功  在對應的頁面應該做什麼？
    //目前這裡是判斷 如果我先前的頁面是重 註冊後 近來 會讓使用者選擇要不要先新增好友 如果選擇要 就會進來這裡 如果這邊加入好友成功之後 要讓使用者回到首頁，但是如果只是登入後 然後重首頁進來 加入好友完以後 不要有任何的動作
    [self.navigationController.viewControllers enumerateObjectsUsingBlock:^(UIViewController *controller, NSUInteger idx, BOOL *stop) {
        if ([controller isKindOfClass:[SelectFiedViewController class]]) {
            [self.navigationController popToViewController:controller animated:YES];
            *stop = YES;
        }
    }];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return self.friendRosterVcard.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"AddressCell";
    
    AddressCell *addressCell = (AddressCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (addressCell == nil) {
        
        [tableView registerNib:[UINib nibWithNibName:@"AddressCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
        
        addressCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    }
    
    
    if (![self.friendRosterVcard[indexPath.row][@"PHOTO_PATH"]isEqualToString:@""]&& self.friendRosterVcard[indexPath.row][@"PHOTO_PATH"] != nil) {
        addressCell.imageView.image = [UIImage imageWithContentsOfFile:self.friendRosterVcard[indexPath.row][@"PHOTO_PATH"]];
    }else
    {
        addressCell.imageView.image = [UIImage imageNamed:@"dficon_user"];
    }
    
    addressCell.textLabel.text = self.friendRosterVcard[indexPath.row][@"NICKNAME"];
    addressCell.detailTextLabel.text = self.friendRosterVcard[indexPath.row][@"Name"];

    NSLog(@"%@",self.friendRosterVcard[indexPath.row]);
    
    
    if ([self.selectCellSet containsObject:self.friendRosterVcard[indexPath.row]]) {
        addressCell.accessoryType = UITableViewCellAccessoryCheckmark;
    }else{
        addressCell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    return addressCell;
    
    // Configure the cell...
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self willChangeValueForKey:@"selectCellSet"];

    AddressCell *addressCell = (AddressCell*)[tableView cellForRowAtIndexPath:indexPath];

    if ([self.selectCellSet containsObject:self.friendRosterVcard[indexPath.row]]) {
        [self.selectCellSet removeObject:self.friendRosterVcard[indexPath.row]];
        addressCell.accessoryType = UITableViewCellAccessoryNone;

    }else{
        [self.selectCellSet addObject:self.friendRosterVcard[indexPath.row]];
        addressCell.accessoryType = UITableViewCellAccessoryCheckmark;

    }

    [self didChangeValueForKey:@"selectCellSet"];
}
-(void)alertViewCancel:(UIAlertView *)alertView
{
    //判斷 如果成功  在對應的頁面應該做什麼？
    //目前這裡是判斷 如果我先前的頁面是重 註冊後 近來 會讓使用者選擇要不要先新增好友 如果選擇要 就會進來這裡 如果這邊加入好友成功之後 要讓使用者回到首頁，但是如果只是登入後 然後重首頁進來 加入好友完以後 不要有任何的動作
    [self.navigationController.viewControllers enumerateObjectsUsingBlock:^(UIViewController *controller, NSUInteger idx, BOOL *stop) {
        if ([controller isKindOfClass:[SelectFiedViewController class]]) {
            [self.navigationController popToRootViewControllerAnimated:YES];
            *stop = YES;
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//加入好友
- (IBAction)joinFriendEvent:(id)sender {
    
    NSLog(@"%@",self.selectCellSet);
    
    NSMutableArray *array = [[NSMutableArray alloc]initWithCapacity:0];
    for (NSDictionary *dict in [self.selectCellSet allObjects]) {
        [array addObject:dict[@"jid"]];
    }
    //增加朋友delegate
    [AddFriend sharedInstance].delegate = self;
    
    //增加朋友
    [[AddFriend sharedInstance]addFreindForJid:array];

}
#pragma Tank AddFriendDelegate 增加朋友完畢後的delegate
-(void)AddFriendResult:(id)responseObject
{
    NSLog(@"成功");
    
    //判斷 如果成功  在對應的頁面應該做什麼？
    //目前這裡是判斷 如果我先前的頁面是重 註冊後 近來 會讓使用者選擇要不要先新增好友 如果選擇要 就會進來這裡 如果這邊加入好友成功之後 要讓使用者回到首頁，但是如果只是登入後 然後重首頁進來 加入好友完以後 不要有任何的動作
    [self.navigationController.viewControllers enumerateObjectsUsingBlock:^(UIViewController *controller, NSUInteger idx, BOOL *stop) {
        if ([controller isKindOfClass:[SelectFiedViewController class]]) {
            [self.navigationController popToRootViewControllerAnimated:YES];
            *stop = YES;
        }
    }];
}

-(void)errorAddFriend
{
    NSLog(@"失敗");
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
